package utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;


public class XmlDistributorsParser {
	 private static final String ns = null;
	 public ArrayList<Pair> parse(InputStream in) throws XmlPullParserException, IOException {   
		 try {
         XmlPullParser parser = Xml.newPullParser();
         parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);       
         parser.setInput(in , null);
         parser.nextTag();       
         return readDistributorsXml(parser); 
	 } finally {
         in.close();
     }
 }
	 
	 private ArrayList<Pair> readDistributorsXml(XmlPullParser parser) throws XmlPullParserException, IOException {
		 parser.require(XmlPullParser.START_TAG, ns, "data");
		 ArrayList<Pair> distrb = null;
		 while (parser.next() != XmlPullParser.END_TAG) {
			 if (parser.getEventType() != XmlPullParser.START_TAG) {
	                continue;
	            }
			 String name = parser.getName();
			 if (name.equals("distributors")) {
				 distrb = readDistributors(parser) ;
				 
			 }
	            
	            else{
	            	XmlTemplateParser.skip(parser);
	            }
		 }
		 return distrb;
	 }
	 
	 private ArrayList<Pair> readDistributors(XmlPullParser parser) throws IOException, XmlPullParserException {
	    	ArrayList<Pair> list= new ArrayList<Pair>();
	        parser.require(XmlPullParser.START_TAG, ns, "distributors");
	        while (parser.next() != XmlPullParser.END_TAG) {
	            if (parser.getEventType() != XmlPullParser.START_TAG) {
	                continue;
	            }
	            String name = parser.getName();
	            if (name.equals("distributor")) {
	            	 list.add(readDistributor(parser)) ;}
	            
	        	 else {
	        		 XmlTemplateParser.skip(parser);
	            }
	        }

	        return list;
	    }
	 
	 private OrderedPair <String, String> readDistributor (XmlPullParser parser)throws IOException, XmlPullParserException {
		 String key = null ; 
		 String value = null ; 	
		 parser.next();
	     parser.next();
		 parser.require(XmlPullParser.START_TAG, ns, "postname");
	      key= XmlTemplateParser.readText(parser);
	        parser.require(XmlPullParser.END_TAG, ns, "postname");
	        parser.next();
	        parser.next();
	        parser.require(XmlPullParser.START_TAG, ns, "postcode");     
	        value = XmlTemplateParser.readText(parser);
	        parser.require(XmlPullParser.END_TAG, ns, "postcode");
	        parser.next();
	        parser.next();
	        OrderedPair < String, String> supplier = new  OrderedPair< String, String>(key,value);
		 return  supplier;
	 }
	  
	 
}
